<template>
  <div style="padding: 1rem;">
    <el-row v-if="queryForm">
      <el-col :span="24" class="col_1">
        <span class="demonstration" style="line-height:2rem">
          进度查询
          <el-icon class="el-icon-search" />
        </span>
        <el-container class="search-company">
          <el-form v-model="queryForm" :inline="true" class="demo-form-inline" label-width="80px">
            <el-form-item label="查询类型">
              <ConferTypeSelector v-model="queryForm.conferenceType" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="queryForm.start"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="queryForm.end"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
          <el-form v-model="filterForm" :inline="true" class="demo-form-inline" label-width="80px">
            <el-form-item label="次数 (≥)">
              <el-input v-model="filterForm.times" />
            </el-form-item>
            <el-form-item label="时长 (≥)">
              <el-input v-model="filterForm.hours" />
            </el-form-item>
            <el-switch
              v-model="showByTree"
              style="float: right;margin-right: 1.5rem;margin-top:0.8rem;"
              active-color="#13ce66"
              inactive-color="#cccccc"
              active-text="按单位建制显示"
            />
          </el-form>
          <el-header class="search-header">
            <el-progress
              type="line"
              :percentage="ptg"
              :text-inside="true"
              :stroke-width="20"
              :color="colors"
              :format="personProgressFormat"
            />
          </el-header>
          <el-row v-if="searchResultForTable" v-loading="searchLoading">
            <el-col
              v-for="item in Object.keys(searchResultForTable)"
              v-show="!showByTree"
              :key="item"
              :span="12"
              class="search-main"
            >
              <el-header>
                <h4 class="table-title">{{ item==='finish'?'':'未' }}完成单位名单</h4>
                <el-table :data="searchResultForTable[item]" height="27rem" border>
                  <el-table-column label="单位" prop="company">
                    <template slot-scope="{row}">
                      <CompanyFormItem :id="row.company" />
                    </template>
                  </el-table-column>
                  <el-table-column label="次数" prop="count" sortable />
                  <el-table-column label="时长">
                    <template slot-scope="{row}">{{ Math.round(row.length/3600) }}</template>
                  </el-table-column>
                </el-table>
              </el-header>
            </el-col>
            <ComanyStatisticsTree v-show="showByTree" :data.sync="searchResultForTree" />
          </el-row>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { parseTime } from '@/utils'
import {
  getIndicatorList,
  getConferenceStatistics
} from '@/api/zzxt/party-conference/confer-indicator'
export default {
  name: 'ProgressStatistics',
  components: {
    ConferTypeSelector: () =>
      import('@/components/Party/ConferType/ConferTypeSelector'),
    ComanyStatisticsTree: () => import('./CompanyStatisticsTree/index'),
    CompanyFormItem: () => import('@/components/Company/CompanyFormItem')
  },
  data() {
    return {
      searchLoading: false,
      queryForm: this.createForm(),
      filterForm: {},
      percentage: 0,
      colors: [
        { color: '#f56c6c', percentage: 20 },
        { color: '#e6a23c', percentage: 40 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 80 },
        { color: '#6f7ad3', percentage: 100 }
      ],
      searchResult: null,
      searchResultForTable: null,
      searchResultForTree: null,
      showByTree: false,
      defaultProps: {
        children: 'children',
        label: 'company'
      }
    }
  },
  computed: {
    currentCompany() {
      return this.$store.state.user.globalCompany
    },
    ptg() {
      if (!this.searchResult) return 0
      const re = this.searchResult
      const finish = re.finishCount || 0
      const total = re.childrenTotalCount || 1
      const ptg = (finish / total) * 100
      return ptg
    }
  },
  watch: {
    searchResult: {
      handler(val) {
        val.company = this.currentCompany.slice(0, 2)
        const re = JSON.parse(JSON.stringify(val))
        const arr = []
        arr.push(this.SetResultTree(re))
        this.searchResultForTree = arr
        this.personProgressFormat()
      }
    },
    queryForm: {
      handler(val) {
        if (this.currentCompany) this.progressQuery()
      },
      deep: true,
      immediate: true
    },
    filterForm: {
      handler(val) {
        if (this.currentCompany) this.progressQuery()
      },
      deep: true
    },
    'queryForm.conferenceType': {
      handler(val) {
        if (this.currentCompany) this.indicatorInit(val)
      },
      immediate: true
    },
    currentCompany: {
      handler(val) {
        if (val) this.progressQuery()
      },
      immediate: true
    }
  },
  mounted() {
    this.$store.dispatch('party/initDictionary')
  },
  methods: {
    SetResultTree(val) {
      let ar = []
      const keys = Object.keys(val.children)
      if (keys.length > 0) {
        ar = keys.map(key => {
          val.children[key].company = key
          return this.SetResultTree(val.children[key])
        })
      }
      val.children = ar
      return val
    },
    progressQuery() {
      this.searchLoading = true
      const company = this.currentCompany.slice(0, 2)
      getConferenceStatistics(Object.assign(this.queryForm, { company })).then(
        data => {
          const re = data.model
          this.searchResultForTable = { finish: [], unfinish: [] }
          this.dataClean(re)
          this.searchResult = re
          this.searchLoading = false
        }
      )
    },
    dataClean(re) {
      const self = re.self
      re.finishCount = 0
      if (self.length > 0) {
        const finish = this.getIsFinish(self)
        re.finish = finish
        re.self.forEach(ar =>
          this.searchResultForTable[ar.finish ? 'finish' : 'unfinish'].push(ar)
        )
        re.finishCount += finish
      }
      if (re.childrenCount > 0) {
        Object.keys(re.children).forEach(compamy => {
          const item = re.children[compamy]
          re.finishCount += this.dataClean(item)
        })
      }
      return re.finishCount
    },
    getIsFinish(self) {
      const standard = this.filterForm
      let finish = 0
      self.forEach(item => {
        item.finish =
          item.count >= standard.times && item.length >= standard.hours * 3600
        finish += item.finish
      })
      return finish
    },
    createForm() {
      const start = new Date()
      const end = new Date(start)
      start.setDate(1)
      end.setMonth(end.getMonth() + 1)
      end.setDate(0)
      const data = {
        start: parseTime(start, '{y}-{m}-{d}'),
        end: parseTime(end, '{y}-{m}-{d}'),
        conferenceType: 1
      }
      return data
    },
    indicatorInit(type) {
      const query_list = {
        period: 4,
        conferenceType: type,
        companyCode: this.currentCompany
      }
      getIndicatorList(query_list).then(data => {
        if (data.list.length === 0) return
        const obj = data.list[0]
        const filterData = {
          times: obj.requireTimes,
          hours: obj.requireHours
        }
        this.filterForm = filterData
      })
    },
    educationProgressFormat(percentage) {
      return percentage === 100
        ? '已完成'
        : '单位本月已完成：' + `${percentage}%`
    },
    ProcessTitle(val) {
      return '完成进度:' + val + '%'
    },
    personProgressFormat(percentage) {
      return percentage === 100
        ? '所有单位已完成'
        : '完成单位占比：' + `${percentage}%`
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../home/style.scss';
.row_company {
  height: 40rem;
}
.table-title {
  font-weight: 500px;
  margin-top: 1rem;
  margin-bottom: 1rem;
  text-align: center;
}
</style>
